package com.example.duihua.controller;

import com.example.duihua.entity.Conversation;
import com.example.duihua.entity.User;
import com.example.duihua.service.ConversationService;
import com.example.duihua.service.UserService;
import com.example.duihua.utils.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/conversations")
public class ConversationController {

    @Autowired
    private ConversationService conversationService;
    
    @Autowired
    private UserService userService;

    /**
     * 获取当前用户的所有会话列表
     */
    @GetMapping
    public ResponseEntity<?> getConversations(@AuthenticationPrincipal UserDetails userDetails) {
        User user = userService.findByUsername(userDetails.getUsername());
        if (user == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
        }
        
        List<Conversation> conversations = conversationService.getUserConversations(user.getId());
        // 组装 clientId，便于前端稳定解析
        for (Conversation c : conversations) {
            if ("PRIVATE".equals(c.getType())) {
                Long a = Math.min(c.getUserId(), c.getTargetId());
                Long b = Math.max(c.getUserId(), c.getTargetId());
                c.setClientId("private_" + a + "_" + b);
            } else if ("GROUP".equals(c.getType())) {
                c.setClientId("group_" + c.getTargetId());
            }
        }
        return ResponseEntity.ok(ApiResponse.success(conversations));
    }

    /**
     * 获取指定会话详情
     */
    @GetMapping("/{conversationId}")
    public ResponseEntity<?> getConversation(
            @PathVariable String conversationId,
            @AuthenticationPrincipal UserDetails userDetails) {
        
        User user = userService.findByUsername(userDetails.getUsername());
        if (user == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
        }
        
        Conversation conversation = conversationService.findByIdAndUserId(conversationId, user.getId());
        if (conversation == null) {
            return ResponseEntity.notFound().build();
        }
        
        return ResponseEntity.ok(ApiResponse.success(conversation));
    }

    /**
     * 删除会话
     */
    @DeleteMapping("/{conversationId}")
    public ResponseEntity<?> deleteConversation(
            @PathVariable String conversationId,
            @AuthenticationPrincipal UserDetails userDetails) {
        
        User user = userService.findByUsername(userDetails.getUsername());
        if (user == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
        }
        
        boolean success = conversationService.deleteConversation(conversationId, user.getId());
        if (success) {
            return ResponseEntity.ok(ApiResponse.success("会话已删除"));
        } else {
            return ResponseEntity.badRequest().body(ApiResponse.error("删除会话失败"));
        }
    }
    
    /**
     * 标记会话为已读（重置未读消息数量）
     */
    @PutMapping("/{conversationId}/read")
    public ResponseEntity<?> markAsRead(
            @PathVariable String conversationId,
            @AuthenticationPrincipal UserDetails userDetails) {
        
        User user = userService.findByUsername(userDetails.getUsername());
        if (user == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
        }

        // 兼容带前缀的 clientId（private_a_b / group_x），并确保会话行存在
        String dbId = conversationId;
        String type = null;
        Long targetId = null;
        try {
            if (conversationId.startsWith("group_")) {
                type = "GROUP";
                targetId = Long.parseLong(conversationId.replace("group_", ""));
                dbId = "group_" + targetId;
            } else if (conversationId.startsWith("private_")) {
                type = "PRIVATE";
                String[] parts = conversationId.replace("private_", "").split("_");
                Long a = Long.parseLong(parts[0]);
                Long b = Long.parseLong(parts[1]);
                Long me = user.getId();
                targetId = me.equals(a) ? b : a;
                dbId = Math.min(a, b) + "_" + Math.max(a, b);
            } else if (conversationId.matches("\\d+_\\d+")) {
                type = "PRIVATE";
                String[] parts = conversationId.split("_");
                Long a = Long.parseLong(parts[0]);
                Long b = Long.parseLong(parts[1]);
                Long me = user.getId();
                targetId = me.equals(a) ? b : a;
                dbId = conversationId;
            }
        } catch (Exception e) {
            // ignore parse errors; fall back to original id
        }

        // 如果会话不存在则创建（以便能够重置未读数）
        Conversation existing = conversationService.findByIdAndUserId(dbId, user.getId());
        if (existing == null && type != null && targetId != null) {
            Conversation conv = new Conversation();
            conv.setId(dbId);
            conv.setUserId(user.getId());
            conv.setTargetId(targetId);
            conv.setType(type);
            conv.setUnreadCount(0);
            conversationService.saveOrUpdate(conv);
        }

        boolean success = conversationService.resetUnreadCount(dbId, user.getId());
        if (success) {
            return ResponseEntity.ok(ApiResponse.success("会话已标记为已读"));
        } else {
            return ResponseEntity.badRequest().body(ApiResponse.error("标记会话为已读失败"));
        }
    }
    
    /**
     * 更新会话未读消息数量
     */
    @PutMapping("/{conversationId}/unread")
    public ResponseEntity<?> updateUnreadCount(
            @PathVariable String conversationId,
            @RequestBody Map<String, Integer> request,
            @AuthenticationPrincipal UserDetails userDetails) {
        
        Integer count = request.get("count");
        if (count == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("未读消息数量不能为空"));
        }
        
        User user = userService.findByUsername(userDetails.getUsername());
        if (user == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("用户不存在"));
        }
        
        boolean success = conversationService.updateUnreadCount(conversationId, user.getId(), count);
        if (success) {
            return ResponseEntity.ok(ApiResponse.success("未读消息数量已更新"));
        } else {
            return ResponseEntity.badRequest().body(ApiResponse.error("更新未读消息数量失败"));
        }
    }
}
